/**
 * Created by apple on 2019.01.26.
 */
var DBFactory = require('../db/mysql_db');
var MallDao = module.exports;
var PostHelper = require('../util/postHelper');
var crypto = require('crypto');

//调用微领商城接口查询用户零钱余额
MallDao.getBalanceByWL = function (data, cb) {
    data.key = 'JF201922514227251';
    data.secret = 'PYQfDB2WmszH58Fn';
    data.platInfo = 'http://front.xmvling.com/api/get_user_cash.html';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            api: 'check_score',
            user_id: data.recharge_phone,
            key: data.key,
            secret: data.secret
        }
    };

    requestPlatBaseWL(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }));
}

//查询DS用户积分充值上限
MallDao.search_score_limit = function (data, cb) {

    data.platInfo = 'http://ja.longliqi.com/API/getUserScoreLimit'; //待更改
    data.key = 'JF2019326162845582';
    data.secret = 'JBj2xxQjBP6554Hp';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            key: data.key,
            time: new Date().getTime().toString(),
            api: 'score_limit',
            user_id: data.recharge_phone,
            secret: data.secret
        }
    };

    requestPlatByDS(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }));
}

function requestPlatByDS(data, cb) {
    var needParam = ['platInfo', 'link_param'];
    if (checkHasParamAndCb(data, needParam, cb).err) return;

    var link_param = data.link_param;
    var link_url = data.platInfo;
    var secret = data.link_param.secret;
    delete link_param.secret;

    if (!link_url) {
        cb('操作异常 Err:Info setting error ');
        return;
    }
    console.log(link_param);

    var requestParam = getSortObjByAsciiWithObj(link_param, secret); //生成带加密sign的请求参数
    console.log(requestParam);

    PostHelper.baseRequestByWL(link_url, requestParam, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台' + link_param.key + '发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ' + link_param.api);
            return;
        }
        cb(null, data);
    });
}

function requestPlatBaseWL(data, cb) {

    var needParam = ['platInfo', 'link_param'];
    if (checkHasParamAndCb(data, needParam, cb).err) return;

    var link_param = data.link_param;
    var link_url = data.platInfo;
    var secret = data.link_param.secret;
    delete link_param.secret;
    link_param.time = new Date().getTime().toString();

    if (!link_url) {
        cb('操作异常 Err:Info setting error ');
        return;
    }

    console.log(link_param);

    var requestParam = getSortObjByAsciiWithObj(link_param, secret); //生成带加密sign的请求参数

    PostHelper.baseRequestByWL(link_url, requestParam, function (err, data) {
        if (err) {
            cb('访问出错，请联系客服 Err:request plat failed ' + link_param.api);
            return;
        }
        cb(null, data);
    });
}

MallDao.recharge_encryption = function (data, cb) {
    data.key = 'JF2019326162845582';
    data.secret = 'JBj2xxQjBP6554Hp';

    var param = {
        link_param: {
            api: 'recharge_encryption',
            key: data.key,
            orderCode: data.orderCode,
            recharge_phone: data.recharge_phone,
            user_phone: data.user_phone,
            app_sid: data.app_sid,
            score: data.score,
            secret: data.secret,
            time: data.time
        }
    }

    requestEncryption(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }));
}

function requestEncryption(data, cb) {

    var link_param = data.link_param;
    var secret = data.link_param.secret;
    delete link_param.secret;

    console.log(link_param);

    var requestParam = getSortObjByAsciiWithObj(link_param, secret); //生成带加密sign的请求参数

    cb(null, requestParam);
}

/**
 *扣除微领用户对应平台的零钱
 */
MallDao.delBalanceByWL = function (data, cb) { //调用接口查询用户积分
    data.key = 'JF201922514227251';
    data.secret = 'PYQfDB2WmszH58Fn';
    data.platInfo = 'http://front.xmvling.com/api/taobao_charge_back.html';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            phone: data.recharge_phone,
            key: data.key,
            score: data.score,
            secret: data.secret
        }
    };

    requestdelPlatWL(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }))
}

function requestdelPlatWL(data, cb) {

    var needParam = ['platInfo', 'link_param'];
    if (checkHasParamAndCb(data, needParam, cb).err) return;

    var link_param = data.link_param;
    var link_url = data.platInfo;
    var secret = data.link_param.secret;
    delete link_param.secret;
    link_param.time = new Date().getTime().toString();

    if (!link_url) {
        cb('操作异常 Err:Info setting error ');
        return;
    }

    // console.log(link_param);

    var requestParam = getSortObjByAsciiWithObj(link_param, secret); //生成带加密sign的请求参数

    // console.log(requestParam);

    PostHelper.baseRequestByWL(link_url, requestParam, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台' + link_param.key + '发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ' + link_param.api);
            return;
        }
        cb(null, data);
    });
}

//返回拼接上sign的请求对象
function getSortObjByAsciiWithObj(obj, secret) {

    var sortArrStr = getSortStrByAsciiWithObj(obj); //组成按字母顺序排序的字符串

    var waitSecretStr = secret + sortArrStr + secret; //使用前后加secret的方式拼接待加密字符串   waitStr="ek93nkdkswWjfetkey=JF201811212112125phone=18605996973score=11time=1545449321396ek93nkdkswWjfet"

    var md5 = crypto.createHash('md5');
    md5.update(waitSecretStr); //waitSign="c51951be9421b1dd93f9938555d71da5"
    var stringSign = md5.digest('hex');
    var sign = stringSign.toLocaleLowerCase(); //sign="c51951be9421b1dd  93f9938555d71da5"
    obj.sign = sign;
    return obj;
}

//构造按Ascii码顺序组成的字符串
function getSortStrByAsciiWithObj(obj) {
    var arr = [];
    for (var key in obj) {
        arr.push(key);
    }
    var sortArr = getsParaFromArr(arr); //返回按字母顺序排序的数组
    var sortArrStr = '';
    sortArr.forEach(function (key) {
        var item = {};
        item[key] = obj[key];
        sortArrStr += key + '=' + obj[key];
    });

    // console.log('sortArrStr = ' + sortArrStr);
    return sortArrStr; //str="key=JF201811212112125phone=18605996973score=11time=1545449321396"
}

//传入数组，返回按Ascii码排序的数组
function getsParaFromArr(sParaTemp) {
    var sPara = [];
    //除去数组中的空值和签名参数
    for (var i1 = 0; i1 < sParaTemp.length; i1++) {
        var value = sParaTemp[i1];
        if (value == null || value == "" || value == "sign") {
            continue;
        }
        sPara.push(value);
    }
    sPara = sPara.sort();
    return sPara;
}